package com.colis.quartz.component;

import com.colis.quartz.module.sms.QuartzTask;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * <p> 描述： </p>
 *
 * @author wlp
 * @version 1.0.0
 * @date 2022/1/14 15:09
 */
@Data
@Slf4j
public class MyQuartzSchedule implements Runnable {

    private QuartzTask quartzTask;
    private Method beanMethod;
    private Object beanObject;
    private Class<?> targetClass;


    @Override
    public void run() {
        try {
            targetClass = Class.forName(quartzTask.getTargetBean());
            beanObject = SpringTool.getBean(targetClass);
        } catch (ClassNotFoundException e) {
            beanObject = SpringTool.getBean(quartzTask.getTargetBean());
        }
        String taskParams = quartzTask.getParams();
        try {
            if (StringUtils.isNotBlank(taskParams)) {
                beanMethod = beanObject.getClass().getDeclaredMethod(quartzTask.getTargetMethod(), String.class);
            } else {
                beanMethod = beanObject.getClass().getDeclaredMethod(quartzTask.getTargetMethod());
            }
            if (quartzTask.getQuartzType().equals(1)) {
                ReflectionUtils.makeAccessible(beanMethod);
                if (StringUtils.isNotBlank(taskParams)) {
                    beanMethod.invoke(beanObject, taskParams);
                } else {
                    beanMethod.invoke(beanObject);
                }
            } else {
                log.info("其他方式处理方式");
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            log.error("运行异常啦！", e);
        }
    }
}
